import utils from '../utils'
import {GeoJSON} from './index.js'
import { PathImporter } from '../paths'

function GeoJSONParser(opts) {
  const idField = opts.id_field || GeoJSON.ID_FIELD
  const importer = new PathImporter(opts)
  this.parseObject = function(o) {
    let geom = null
    let rec = null
    if (!o || !o.type) {
      // not standard GeoJSON -- importing as null record
      // (useful when parsing GeoJSON generated internally)
      geom = null
    } else if (o.type == 'Feature') {
      geom = o.geometry
      rec = o.properties || {}
      if ('id' in o) {
        rec[idField] = o.id
      }
    } else {
      geom = o
    }
    // TODO: improve so geometry_type option skips features instead of creating null geometries
    importer.startShape(rec)
    if (geom) GeoJSON.importGeometry(geom, importer, opts)
  }
  this.done = function() {
    return importer.done()
  }
}
function importGeoJSON(src, optsArg) {
  const opts = optsArg || {}
  const supportedGeometries = Object.keys(GeoJSON.pathImporters)
  const srcObj = utils.isString(src) ? JSON.parse(src) : src
  const importer = new GeoJSONParser(opts)
  let srcCollection, dataset

  // Convert single feature or geometry into a collection with one member
  if (srcObj.type == 'Feature') {
    srcCollection = {
      type: 'FeatureCollection',
      features: [srcObj]
    }
  } else if (utils.contains(supportedGeometries, srcObj.type)) {
    srcCollection = {
      type: 'GeometryCollection',
      geometries: [srcObj]
    }
  } else {
    srcCollection = srcObj
  }
  (srcCollection.features || srcCollection.geometries || []).forEach(importer.parseObject)
  dataset = importer.done()
  importCRS(dataset, srcObj) // TODO: remove this
  return dataset
}
function importCRS(dataset, jsonObj) {
  if ('crs' in jsonObj) {
    dataset.info.input_geojson_crs = jsonObj.crs
  }
}
export {
  GeoJSONParser,
  importCRS,
}
export default {
  importGeoJSON,
}